import React, { useEffect, useState } from 'react';
import { Button, Form, message, Checkbox, Row, Col, } from 'antd';
// import { DICT_TYPE, getOptions } from '@/global/service';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormCheckbox,
  ProFormSelect,
  ProFormRadio,
  ProFormDateTimePicker,
  ProFormDigit
} from '@ant-design/pro-form';
import { history } from 'umi';
// import {
//   MANUAL_PUSH,
//   ,
//   JUMPWAY_MODULE,
//   AUDIENCETYPE_ALL,
//   ,
//   AUDIENCETYPE_CLASS,
// } from '../../constants';
import { addPaper, getByAId } from '../service';
import moment from 'moment';

declare const ValidateStatuses: ['success', 'warning', 'error', 'validating', '', true];
declare type ValidateStatus = typeof ValidateStatuses[number];

interface AddFormProps {
  modalVisible: boolean;
  modalType:string;
  testId:number;
  onCancel: () => void;
  onReload: () => void;
}

const requireStyle = {
  color: '#ff4d4f',
  marginRight: '4px',
  fontSize: '14px',
  fontFamily: 'SimSun, sans-serif',
};

const AddForm: React.FC<AddFormProps> = (props) => {
  const [form] = Form.useForm();
  const { modalVisible, modalType, testId, onCancel, onReload } = props;
  const [showData, setShowData] = useState(true);
  const [audienceType, setAudienceType] = useState();

  const [batchValidStatus, setBatchValidStatus] = useState<any>('');
  const [batchErrorText, setBatchErrorText] = useState<string>('');

  const [alistValidStatus, setAlistValidStatus] = useState<any>('');
  const [alistErrorText, setAlistErrorText] = useState<string>('');

  const [validateTotalStatus, setValidateTotalStatus] = useState<any>('');
  const { id } = history.location.query || {}

  useEffect(() => {
    if (modalType == 'edit' ) {
      modalVisible && fetchData();
    } 
  }, [modalVisible]);
  const fetchData = async () => {
    const res = await getByAId({ id:testId });
    let result = res.result;
    form.setFieldsValue({
      name: result.name,
      level: result.level,
      startTime: moment(result.startTime * 1000),
      complateAward: result.complateAward,
      passAward: result.passAward,
      fullAward: result.fullAward,
    });
    result.isEnableAward == 1?setShowData(true):setShowData(false)
    console.log(moment(result.startTime * 1000))



    // setData(result);
  };

  const batchStatusHanlder = (status: ValidateStatus, text: string) => {
    setBatchValidStatus(status);
    setBatchErrorText(text);
  };
  // const validArrListHanlder = function (val: any, handler: any) {
  //   if (audienceType === '') {
  //     return validPhoneListHandler(val, handler);
  //   }
  //   if (audienceType === AUDIENCETYPE_CLASS) {
  //     return validIdListHandler(val, handler);
  //   }
  // };
  // const validPhoneListHandler = function (
  //   phones: string,
  //   statusHandler: (status: ValidateStatus, text: string) => void,
  // ) {
  //   if (!phones) {
  //     statusHandler('error', '请输入推送的手机号');
  //     return false;
  //   }
  //   var arr = phones.split('\n');
  //   for (var i = 0; i < arr.length; i++) {
  //     if (arr[i] && isNaN(Number(arr[i]))) {
  //       statusHandler('error', '手机号仅可输入数字，请检查输入');
  //       return false;
  //     }
  //   }
  //   var isValidLen = phones.split('\n');
  //   var unValidStr = '手机号格式不正确:';
  //   var hasUnValidPhone = false;
  //   for (var l = 0; l < isValidLen.length; l++) {
  //     if (
  //       isValidLen[l].length > 0 &&
  //       (isValidLen[l].length !== 11 || isValidLen[l].substr(0, 1) !== '1')
  //     ) {
  //       hasUnValidPhone = true;
  //       unValidStr += isValidLen[l] + '，';
  //     }
  //   }
  //   if (hasUnValidPhone) {
  //     statusHandler('error', unValidStr);
  //     return false;
  //   }
  //   return true;
  // };
  // const validIdListHandler = function (
  //   ids: string,
  //   statusHandler: (status: ValidateStatus, text: string) => void,
  // ) {
  //   if (!ids) {
  //     statusHandler('error', '请输入推送的课程ID');
  //     return false;
  //   }
  //   var arr = ids.split('\n');
  //   for (var i = 0; i < arr.length; i++) {
  //     if (arr[i] && isNaN(Number(arr[i]))) {
  //       statusHandler('error', '课程ID仅可输入数字，请检查输入');
  //       return false;
  //     }
  //   }
  //   return true;
  // };

  // const combinationText = (text: string) => {
  //   let curContent = form.getFieldValue('content');
  //   if (curContent && curContent.length + text.length > 100) {
  //     message.error('推送内容超过100字符限制');
  //     return;
  //   }
  //   form.setFieldsValue({ content: curContent ? curContent + text : text });
  // };
  const onFinish = async function () {
    const values = form.getFieldsValue();
    
   
    // if (alistValidStatus == 'error') {
    //   return;
    // }
    // if (
    //   audienceType != AUDIENCETYPE_ALL &&
    //   validArrListHanlder(values['aliasList'], batchStatusHanlder) === false
    // ) {
    //   return;
    // }

    // batchStatusHanlder(true, '');
    // if (audienceType != AUDIENCETYPE_ALL) {
    //   values.aliasList = values.aliasList.split('\n');

    //   let _aliasList = [];
    //   values.aliasList.forEach((val) => {
    //     val && _aliasList.push(val);
    //   });
    //   values.aliasList = _aliasList.join(',');
    // }
    values.startTime = moment(new Date(values.startTime)).format('YYYY-MM-DD HH:mm:00');
    values.productId = id;
    values.isEnableAward = showData;
    if(!showData){
      values.complateAward = null
      values.passAward = null
      values.fullAward = null
    }
    
    modalType == 'add'?values.id = '' :values.id = testId;
    
    console.log(values)
    const res = await addPaper(values);
    if (res.code === 200) {
      form.resetFields();
      // setJumpWayType();
      // setAudienceType();
      onReload();
      onCancel();
      message.success('添加成功');
    } else {
      if (res.message.startsWith('500')) {
        batchStatusHanlder('error', res.message.replace('500', ''));
        return;
      }
      message.error(res.message);
    }
  };
  const disabledDate = (current) => {
    return current && current < moment().subtract(1, 'days');
  };
  const disabledHours = () => {
    return [22, 23, 0, 1, 2, 3, 4, 5, 6];
  };
  const onChange = (e) => {
    console.log(`checked = ${e.target.checked}`);
    setShowData(e.target.checked)
  };
  useEffect(() => {
    if (batchValidStatus === 'error' || alistValidStatus === 'error') {
      setValidateTotalStatus('error');
    } else {
      setValidateTotalStatus('');
    }
  }, [batchValidStatus, alistValidStatus]);
  return (
    <ModalForm
      title="新建试卷"
      visible={modalVisible}
      form={form}
      onFinish={onFinish}
      modalProps={{
        onCancel: () => {
          form.resetFields();
          // setJumpWayType();
          // setAudienceType();

          // setAlistErrorText('');
          // setAlistValidStatus(true);

          // batchStatusHanlder(true, '');

          onCancel();
        },
      }}
    >
      <ProFormText
        label="试卷名称"
        name="name"
        fieldProps={{
          maxLength: 15,
        }}
        rules={[
          {
            required: true,
            message: '试卷名称不能为空',
          },
        ]}
        placeholder="请输入试卷名称"
      />
      <ProFormSelect
        name="level"
        label="试卷难度"
        valueEnum={{
          'high': '较高',
          'common': '普通',
          'low': '较低',
          'simple': '简单',
        }}
        placeholder="请选择试卷难度"
        rules={[{ required: true, message: '请选择试卷难度' }]}
      />
      
      
      <ProFormDateTimePicker
        label="开始时间"
        name="startTime"
        width="md"
        fieldProps={{
          format: 'YYYY-MM-DD HH:mm:00',
          // disabledDate,
          // disabledTime: () => {
          //   return {
          //     disabledHours,
          //   };
          // },
        }}
        placeholder="请选择开始时间"
        rules={[
          {
            required: true,
            message: '请选择开始时间',
          }
        ]}
      />
      <Checkbox onChange={onChange} style={{marginBottom:20}} checked={showData}>棋豆奖励</Checkbox>
      {showData &&(
       <Row gutter={30}>
       <Col className="gutter-row" span={8}>
       <ProFormDigit
          label="完成奖励"
          name="complateAward"
          rules={[{ required: true, message: '完成奖励不能为空' }]}
          min={0}
          max={100}
          initialValue={2}
          fieldProps={{ 
            precision: 0,
            controls:false,
            // style: {
            //   width: 70,
            // }
           }}
        />
       </Col>
       <Col className="gutter-row" span={8}>
       <ProFormDigit
          label="及格奖励"
          name="passAward"
          rules={[{ required: true, message: '及格奖励不能为空' }]}
          min={0}
          max={100}
          initialValue={3}
          fieldProps={{ 
            precision: 0,
            controls:false,
            // style: {
            //   width: 70,
            // }
           }}
        />
       </Col>
       <Col className="gutter-row" span={8}>
       <ProFormDigit
          label="满分奖励"
          name="fullAward"
          rules={[{ required: true, message: '满分奖励不能为空' }]}
          min={0}
          max={500}
          initialValue={5}
          fieldProps={{ 
            controls:false,
            precision: 0,
            // style: {
            //   width: 70,
            // }
           }}
        />
       </Col>
       </Row>
      
      
      
      )}
      
    </ModalForm>
  );
};

export default AddForm;
